package com.cicadasmall.support.captch.impl;


import cn.hutool.core.util.IdUtil;
import com.cicadasmall.common.constant.Constant;
import com.cicadasmall.common.exception.ServiceException;
import com.cicadasmall.common.func.Fn;
import com.cicadasmall.common.resp.R;
import com.cicadasmall.support.captch.AbstractValidateCodeService;
import com.google.common.collect.Maps;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.Map;

/**
 * @author jin
 * @date 2019/4/27 14:10
 * @description: 验证码服务
 */
@Slf4j
@Service("imageValidateCodeService")
public class ImageValidateCodeService extends AbstractValidateCodeService {

    @Autowired
    public ImageValidateCodeService(StringRedisTemplate redisTemplate) {
        super(redisTemplate);
    }

    @SneakyThrows
    @Override
    public R create() {
        Captcha captcha = new GifCaptcha(100, 35, 4);
        captcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        captcha.setFont(Captcha.FONT_1, Font.PLAIN,25);
        String key = IdUtil.randomUUID();
        put(buildCacheKey(key), captcha.text());
        Map validInfo = Maps.newHashMap();
        validInfo.put("deviceId", key);
        validInfo.put("base64Image", captcha.toBase64());
        return R.ok(validInfo);
    }


    @Override
    protected String buildCacheKey(String s) {
        if (Fn.isEmpty(s)) {
            throw new ServiceException("参数错误，验证码校验失败！");
        }
        return Constant.PREFIX + Constant.VALIDATE_REDIS_CODE_KEY + s;
    }
}
